/*
 * Copyright (c) 2020 Tenny
 *  typescript-init is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *           http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */
const readline = require('readline');
const colors = require('terminal-simple-colors');

const icons = {
  info: colors.blue('i'),
  success: colors.green('√'),
  warning: colors.yellow('‼'),
  error: colors.red('×')
}

 /**
  * Terminal Loading Tips
  */
class TerminalLoadingTips {

  /**
   * @param {String} text 提示文字
   */
  constructor (text) {
    this.text = text || '';
    this.spinner = {
      frames: ['|', '/', '—', '\\'],
      interval: 200
    };
    this.interval = -1;
    this._frameIndex = 0;
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this._lastText = '';
  }

  /**
   * 渲染文本
   */
  _render (text) {
    this.clear();
    this._lastText = text || this.text;
    this.rl.write(colors.blue(this.spinner.frames[this._frameIndex]) + ' ' + this._lastText);
  }

  /**
   * 开启模拟加载动画
   */
  start () {
    this._render();
    if (this.interval === -1) {
      this.interval = setInterval(() => {
        if (this._frameIndex < this.spinner.frames.length - 1) {
          this._frameIndex++;
        } else {
          this._frameIndex = 0;
        }
        this._render();
      }, this.spinner.interval || 200);
    }
  }

  /**
   * 清除显示的文本
   */
  clear () {
    readline.clearLine(process.stdout, 0);
    readline.moveCursor(process.stdout, -(this._lastText.length * 2 + 2), 0); // * 2 一个中文占两个字符
  }

  /**
   * 重置状态
   */
  _resetStatus (status, text) {
    clearInterval(this.interval);
    this.interval = -1;
    this.clear();
    this._lastText = '';
    this.rl.write(icons[status || 'info'] + ' ' + (text || this.text) + '\r\n');
  }

  /**
   * 停止动画，更改图标为 √，重置文本
   * @param {String} text 显示文本
   */
  succeed (text) {
    this._resetStatus('success', text);
  }

  /**
   * 停止动画，更改图标为 ×，重置文本
   * @param {String} text 
   */
  fail (text) {
    this._resetStatus('error', text);
  }

  /**
   * 停止加载动画
   */
  stop () {
    clearInterval(this.interval);
    this.rl.close();
  }
}

module.exports = function (text) {
  return new TerminalLoadingTips(text);
}
